package com.k.kppcloud.consumer.listener;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class SubscribeNacosService {
    @Resource
    private NacosServiceManager nacosServiceManager;

    @Resource
    private NacosDiscoveryProperties discoveryProperties;

    @Resource
    private NacosServiceDiscovery serviceDiscovery;

    @Resource
    private MyNacosEventListener eventListener;

    private volatile NamingService naming;
    protected static volatile List<String> services = new ArrayList<>();
    protected volatile long time = 30000;

    @PostConstruct
    public void init() {
        try {
            System.out.println("SubscribeNacosService:init");
            naming = nacosServiceManager.getNamingService(discoveryProperties.getNacosProperties());
            services = serviceDiscovery.getServices();
            services.forEach(this::addServiceListener);
            //TODO 定时监听新的 服务
            new Thread(() -> {
                for (; ; ) {
                    try {
                        Thread.sleep(time);
                        List<String> newServices = serviceDiscovery.getServices();
                        for (String service : newServices) {
                            System.out.println("thread: service:" + service);
                            if (!services.contains(service)) {
                                services.add(service);
                                addServiceListener(service);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新的服务添加监听
     *
     * @param serviceName
     */
    public void addServiceListener(String serviceName) {
        try {
            System.out.println("addServiceListener:" + serviceName);
            naming.subscribe(serviceName, "global", eventListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
